/*
 * @Author: zwb
 * @Date: 2019-01-15 17:05:02
 * */

<template>
  <div class="v-container g-white-space">
    <v-header title="支付">
      <span class="back" @click="goBack">
        <i class="el-icon-arrow-left"></i>返回
      </span>
    </v-header>
    <div class="v-main">

      <div class="xc">
        <div class="g-fl">
          <span id="activityName">普通洗车（全车型）</span>
        </div>
        <div class="g-fr">
          <span class="buynum">购买数量 X 1</span>
        </div>
        <div class="g-clearfix"></div>
      </div>
      <div class="tit">订单详情</div>
      <div class="price-box">
        <p>支付金额</p>
        <p class="old-price">原价￥30</p>
        <p id="proPrice" class="new-price">￥8.80</p>
      </div>
      <div class="g-clearfix"></div>
      <div class="rongqi">
        <div id="0" v-on:click="select_type('1')" class="paystyle jg">
          <div class="g-fl">
            <span class="xiche"><img src="@/assets/images/WeChat_pay.png" width="35px">&nbsp;&nbsp;微信支付</span>
          </div>
          <div class="yes g-fr" :class="select_data=='1'?'dui':''"></div>
          <div class="g-clearfix"></div>
        </div>
        <p>*使用平安银行信用卡支付享8.8元优惠体验，其他支付方式需支付原价30元</p>
        <!-- <p>&nbsp;</p>
          <div id="0" v-on:click="select_type('2')" class="paystyle jg">
              <div class="fl"><span class="xiche"><img src="@/assets/images/logo_yl.png" width="35px">&nbsp;&nbsp;银联支付</span></div>
              <div class="yes fr" :class="select_data=='2'?'dui':''" ></div>
              <div class="clearfix"></div>
          </div> -->
      </div>
      <p class="care">*抢购成功后请尽快到盛大网点使用，有效期30天。逾期失效。</p>

      <div class="bottom-submit">
        <mt-button class="my-button round" @click="paySubmit">立即支付</mt-button>
      </div>
    </div>
    <div v-html="frontUP"></div>
  </div>

</template>


<script>
import vHeader from '@/components/Header.vue';
import { Resource } from '@/services/resource';
import { MessageBox } from 'mint-ui';
import $ from 'jquery';
// import Cookies from 'js-cookie';

export default {
  name: 'pay',
  components: {
    vHeader
  },
  data() {
    return {
      select_data: '1', // 选择支付方式
      frontUP: ''
    };
  },
  mounted() {},
  beforeDestroy() {},
  methods: {
    // 返回上一页
    goBack() {
      this.$router.go(-1);
    },
    // 跳转页面
    pageTo(name) {
      this.$router.push(name);
    },
    // 选择支付方式
    select_type(id) {
      this.select_data = id;
    },
    // 立即支付
    paySubmit() {
      let that = this;
      const msgBox = MessageBox({
        title: '提示',
        message: '使用交通银行信用卡支付享5元优惠体验，其他支付方式需支付原价30元',
        showCancelButton: true
      });
      msgBox.then(action => {
        if (action === 'confirm') {
          if (sessionStorage.type == '1') {
            that.weixinPay(); // 公众号
          } else {
            that.formSubmitWX(); // h5支付
          }
        }
      });
    },
    // 微信公众号支付
    weixinPay() {
      pay();
      // let prepay_id;
      let paySign;
      let appId;
      let timeStamp;
      let nonceStr;
      let packageStr;
      let signType;
      /* function GetQueryString(name) {
        let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
        let r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
      } */
      function pay() {
        let curr = new Date();
        let m = curr.getMonth() + 1;
        if (m < 10) {
          m = '0' + m;
        }
        let d = curr.getDate();
        if (d < 10) {
          d = '0' + d;
        }
        let h = curr.getHours();
        if (h < 10) {
          h = '0' + h;
        }
        let mi = curr.getMinutes();
        if (mi < 10) {
          mi = '0' + mi;
        }
        let s = curr.getSeconds();
        if (s < 10) {
          s = '0' + s;
        }
        // let strDatetime = '' + curr.getFullYear() + m + d + h + mi + s;
        // let code = GetQueryString('code');
        Resource.payConfirm.post({}, { type: 1 }).then(res => {
          let data1 = res.resultJson;
          let pnPayStr1 = eval('(' + data1 + ')');
          if (pnPayStr1.resultCode == 'SUCCESS') {
            let pnPayStr = eval('(' + pnPayStr1.pnPayStr + ')');
            appId = pnPayStr.appId;
            paySign = pnPayStr.paySign;
            timeStamp = pnPayStr.timeStamp;
            nonceStr = pnPayStr.nonceStr;
            packageStr = pnPayStr.packageStr;
            signType = pnPayStr.signType;
            callpay();
          } else {
            let _time;
            let _timeNum = 5;
            MessageBox.alert('授权失败,重新获取授权信息<span id="daojishi" style="color:#f37938">5</span>秒').then(action => {
              if (action === 'confirm') {
                clearInterval(_time);
                this.pageTo('home');
              }
            });
            _time = setInterval(function() {
              _timeNum--;
              if (_timeNum >= 0) {
                $('#daojishi').text(_timeNum);
              } else {
                clearInterval(_time);
                this.pageTo('home');
              }
            }, 1000);
          }
        });
      }

      function callpay() {
        if (typeof WeixinJSBridge == 'undefined') {
          if (document.addEventListener) {
            document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
          } else if (document.attachEvent) {
            document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
            document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
          }
        } else {
          onBridgeReady();
        }
      }

      function onBridgeReady() {
        window.WeixinJSBridge.invoke(
          'getBrandWCPayRequest',
          {
            appId: appId, // 公众号名称，由商户传入
            paySign: paySign, // 微信签名
            timeStamp: timeStamp, // 时间戳，自1970年以来的秒数
            nonceStr: nonceStr, // 随机串
            package: packageStr, // 预支付交易会话标识
            signType: signType // 微信签名方式
          },
          function(res) {
            if (res.err_msg == 'get_brand_wcpay_request:ok') {
              // window.location.replace("index.html");
              // window.location.href = "http://baidu.com";
              // window.location.href = 'result.jhtm?time=' + new Date().getTime();
              MessageBox.alert('支付成功！').then(action => {
                if (action === 'confirm') {
                  this.pageTo('order');
                }
              });
            } else if (res.err_msg == 'get_brand_wcpay_request:cancel') {
              let _time;
              let _timeNum = 5;
              MessageBox.alert('支付取消,重新获取授权信息<span id="daojishi" style="color:#f37938">5</span>秒').then(action => {
                if (action === 'confirm') {
                  clearInterval(_time);
                  this.pageTo('home');
                }
              });
              _time = setInterval(function() {
                _timeNum--;
                if (_timeNum >= 0) {
                  $('#daojishi').text(_timeNum);
                } else {
                  clearInterval(_time);
                  this.pageTo('home');
                }
              }, 1000);
            } else if (res.err_msg == 'get_brand_wcpay_request:fail') {
              let _time;
              let _timeNum = 5;
              MessageBox.alert('支付失败,重新获取授权信息<span id="daojishi" style="color:#f37938">5</span>秒').then(action => {
                if (action === 'confirm') {
                  clearInterval(_time);
                  this.pageTo('home');
                }
              });
              _time = setInterval(function() {
                _timeNum--;
                if (_timeNum >= 0) {
                  $('#daojishi').text(_timeNum);
                } else {
                  clearInterval(_time);
                  this.pageTo('home');
                }
              }, 1000);
            } // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
          }
        );
      }
    },
    // 微信H5支付
    formSubmitWX() {
      Resource.payConfirm.post({}, { type: 2 }).then(res => {
        localStorage._source_biaoshi = 1;
        let orderId = res.orderId;
        localStorage.orderId = orderId;
        let html = JSON.parse(res.html);
        window.location.replace(html.mweb_url);
        setTimeout(function() {
          location.reload();
          const msgBox = MessageBox({
            title: '提示',
            message: '若您已支付成功，请点击支付已完成',
            confirmButtonText: '支付已完成',
            cancelButtonText: '再次支付',
            showCancelButton: true
          });
          msgBox.then(action => {
            localStorage._source_biaoshi = 0;
            if (action === 'confirm') {
              Resource.orderQuery.post({}, { orderId: localStorage.orderId }).then(res => {
                let status = res.status;
                if (status != 0) {
                  this.$router.push('order');
                } else {
                  MessageBox.alert('订单未支付，请重新付款<br>若您确定已支付成功，请联系客服');
                }
              });
            }
          });
        }, 1000);
      });
    }
  }
};
</script>

<style lang="less" scoped>
@import url('./pay.less');
</style>
